#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
struct maze{
vector<vector<int>> roads;
vector<int> trap;
int now, obj, n, t;
static int min_t;
maze(){}
maze(int _n, vector<vector<int>> _roads, vector<int> _trap, int _start, int _end): n(_n), now(_start), obj(_end), t(0), roads(_roads), trap(_trap) {}
void _trap(int node){
for(int i=0; i<roads.size(); ++i){
if(roads[i][0]==node || roads[i][1]==node){
int tmp=roads[i][1];
roads[i][1]=roads[i][0];
roads[i][0]=tmp;
}
}
}
bool move(int next){
for(int i=0; i<roads.size(); ++i){
if(roads[i][0]==now && roads[i][1]==next){
now=next;
t+=roads[i][2];
if(obj==now){
if(min_t==-1) min_t=t;
else min_t=min_t>t? t: min_t;
return true;
}
if(find(trap.begin(), trap.end(), now)!=trap.end()) _trap(now);
return false;
}
}
perror("NO ROUTE ERROR");
exit(1);
}
vector<int> moveable(void){
vector<int> movelist;
for(int i=0; i<roads.size(); ++i){
if(roads[i][0]==now) movelist.push_back(roads[i][1]);
}
return movelist;
}
int time(void){
return t;
}
};
int maze::min_t=-1;
void recru(maze m, map<int, int> been){
vector<int> list=m.moveable();
maze tmp=m;
if(list.size()==0) return;
for(int i=0; i<list.size(); ++i){
if(been.at(list[i])>2) continue;
m.move(list[i]);
been[list[i]]++;
recru(m, been);
been[list[i]]--;
m=tmp;
}
}
int solution(int n, int start, int end, vector<vector<int>> roads, vector<int> traps){
int answer;
map<int, int> been;
for(int i=0; i<n; ++i){
been[i+1]=0;
}
been[start]=1;
maze m(n, roads, traps, start, end);
recru(m, been);
answer=m.min_t;
return answer;
}
int main(void){
int n1=3, n2=4, start1=1, start2=1, end1=3, end2=4;
vector<vector<int>> roads1={
{1, 2, 2}, {3, 2, 3}
};
vector<vector<int>> roads2={
{1, 2, 1}, {3, 2, 1}, {2, 4, 1}
};
vector<int> traps1={2};
vector<int> traps2={2, 3};
int result1=solution(n1, start1, end1, roads1, traps1);
int result2=solution(n2, start2, end2, roads2, traps2);
cout<<"result1: "<<result1<<endl;
cout<<"result2: "<<result2<<endl;
return 0;
}